package org.yangjie.cipher;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

import javax.crypto.Cipher;

/**
 * 非对称加密RSA
 * @author YangJie [2017年10月10日 下午3:58:10]
 */
public class RSAUtil {
	
	private static final String ALGORITHM = "RSA"; // 加密算法
	private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding"; // 加密模式

	
	/**
	 * 公钥加密
	 * @param content
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String data, String key) throws Exception {
	    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
	    PublicKey publicKey = KeyFactory.getInstance(ALGORITHM).generatePublic(keySpec);
		Cipher cipher = Cipher.getInstance(TRANSFORMATION);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
	}
	
	/**
	 * 私钥解密
	 * @param content
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String data, String key) throws Exception {
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
	    PrivateKey privateKey = KeyFactory.getInstance(ALGORITHM).generatePrivate(keySpec);
		byte[] bytes = Base64.getDecoder().decode(data);
		Cipher cipher = Cipher.getInstance(TRANSFORMATION);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return new String(cipher.doFinal(bytes));
	}

	/**
	 * 生成密钥对
	 * @return
	 * @throws Exception
	 */
	public static List<String> genKey() throws Exception {
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
		keyPairGenerator.initialize(1024, new SecureRandom());
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
		String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
		return Arrays.asList(publicKey, privateKey);
	}
	

	public static void main(String[] args) throws Exception {

		String data = "rsa 哈哈哈";
		
		List<String> list = genKey();
		String publicKey = list.get(0);
		String privateKey = list.get(1);

		// 公钥
		System.out.println("公钥：" + publicKey);

		// 私钥
		System.out.println("私钥：" + privateKey);

		// 公钥加密
		String code = encrypt(data, publicKey);
		System.out.println("加密后：" + code);

		// 私钥解密
		String text = decrypt(code, privateKey);
		System.out.println("解密后：" + text);
		
	}
	
	
}
